import logging
import threading
from typing import Any

from log import mns_log

mns_log.Log.mns_logging()


# 不适用queue，使用全局变量加数据控制，建立一个线程ID-数据包消息队列
class ThreadScoket:
    def __init__(self) -> None:
        pass


class Message:
    def __init__(self, thread_id, size, source_host, destination_host) -> None:
        self.tread_id = thread_id
        self.size = size
        self.source = source_host
        self.des = destination_host
        # 0：待发送 1：接收成功 2：接收失败
        self.status = 0

    def toString(self) -> str:
        return f'thread_id:{self.tread_id}|size:{self.size}|source_host:{self.source}|destination_host:{self.des}'


class MessageQueue:
    queue = {}
    package_num = 0

    @classmethod
    def set(cls, message: Message):
        if message.tread_id in cls.queue:
            cls.queue[message.tread_id].append(message)
        else:
            cls.queue[message.tread_id] = list([])
            cls.queue[message.tread_id].append(message)

    @classmethod
    def popById(cls, ID) -> Any | None:
        if ID not in cls.queue or not cls.queue[ID]:
            # logging.info("没有元素,ID: " + str(ID))
            return
        else:
            if len(cls.queue[ID]) > 0:
                return cls.queue[ID].pop(0)

    @classmethod
    def getById(cls, ID) -> Any | None:
        if ID not in cls.queue or not cls.queue[ID]:
            # logging.info("没有元素,ID: " + str(ID))
            return
        else:
            return cls.queue[ID][0]

    @classmethod
    def removeById(cls, ID):
        if ID not in cls.queue or not cls.queue[ID]:
            # logging.info("没有元素,ID: " + str(ID))
            return
        else:
            return cls.queue[ID].remove[0]


def test(ID, popID):
    for num in range(1, 10):
        tmp = Message(ID, num, num, num)
        MessageQueue.set(tmp)
        logging.info("set message " + tmp.toString())
        message = MessageQueue.popById(popID)
        if message:
            logging.info("消息：" + message.toString())


class mythread(threading.Thread):
    def __init__(self, ID, popID):
        threading.Thread.__init__(self)
        self.ID = ID
        self.popID = popID

    def run(self):
        test(self.ID, self.popID)


if __name__ == '__main__':
    # MessageQueue.set(Message(1,1,1,1))
    # MessageQueue.set(Message(2,2,2,2))
    # message=MessageQueue.popById(2)
    # print("消息："+message.toString())
    thread1 = mythread(1, 2)
    thread2 = mythread(2, 1)
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    list1 = MessageQueue.queue[1]
    list2 = MessageQueue.queue[2]
    print(len(list1))
    print(len(list2))
    # print(MessageQueue.queue[2][5].toString())
